package com.chinairi.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chinairi.common.annotation.CiccLabel;
import com.chinairi.common.annotation.DoPage;
import com.chinairi.common.utils.RedisUtil;
import com.chinairi.common.utils.UserSession;
import com.chinairi.mall.constant.CiccTableNameEnum;
import com.chinairi.mall.controller.viewobject.ContractMaintainGetVO;
import com.chinairi.mall.controller.viewobject.ContractMaintainVO;
import com.chinairi.mall.dao.ContractFileMapper;
import com.chinairi.mall.dao.ContractMatMapper;
import com.chinairi.mall.dao.ContractServiceMapper;
import com.chinairi.mall.model.*;
import com.chinairi.mall.dao.ContractMaitainMapper;
import com.chinairi.mall.service.IContractMaitainService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinairi.mall.service.modelobject.ContractOfShopRedisMO;
import com.chinairi.mall.service.modelobject.UserInfoToRedisMO;
import com.chinairi.mall.util.CiccRecordUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 合同维护 服务实现类
 * </p>
 *
 * @author Webgasd
 * @since 2020-09-03
 */
@Service
public class ContractMaitainServiceImpl extends ServiceImpl<ContractMaitainMapper, ContractMaitain> implements IContractMaitainService {
    @Autowired
    private ContractMaitainMapper contractMaitainMapper;
    @Autowired
    private ContractFileMapper contractFileMapper;
    @Autowired
    private ContractMatMapper contractMatMapper;
    @Autowired
    private ContractServiceMapper contractServiceMapper;
    @Autowired
    private UserCompanyInfoServiceImpl userCompanyInfoService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SysUserServiceImpl sysUserService;

    public void putRedis() {
        redisUtil.del("contractShopMap");
        List<ContractOfShopRedisMO> contractOfShopRedisMoList = contractMaitainMapper.getContractOfShopRedis();
        if (contractOfShopRedisMoList.size() > 0) {
            Map<String, Object> contractShopMap = new HashMap<>(contractOfShopRedisMoList.size());
            for (ContractOfShopRedisMO contractOfShopRedisMo : contractOfShopRedisMoList) {
                contractShopMap.put(contractOfShopRedisMo.getCsDbid(), contractOfShopRedisMo.getContDbid());
            }
            redisUtil.hmset("contractShopMap", contractShopMap, 3700);
        }

    }

    public Map<Object, Object> getContractShopMapFromRedis() {
        Map<Object, Object> contractShopMapResult = redisUtil.hmget("contractShopMap");
        if (!redisUtil.hasKey("contractShopMap") || contractShopMapResult.size() == 0) {
            putRedis();
        }
        return redisUtil.hmget("contractShopMap");
    }

    /**
     * 获取合同列表
     *
     * @param contractMaintainGetVO
     * @return
     */
    @Override
    @DoPage
    public List<ContractMaintainGetVO> get(ContractMaintainGetVO contractMaintainGetVO) {
        Integer uciCompCharacter = contractMaitainMapper.selectUciCompCharacter(UserSession.getUserId());
        return contractMaitainMapper.getList(contractMaintainGetVO,UserSession.getUserId(),uciCompCharacter);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void config(ContractMaintainVO contractMaintainVO) {
        ContractMaitain contractMaitain = new ContractMaintainVO();
        BeanUtils.copyProperties(contractMaintainVO, contractMaitain);
        ContractFile contractFile = new ContractFile();
        BeanUtils.copyProperties(contractMaintainVO, contractFile);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        contractMaitain.setContDbid(uuid);
        if (contractMaintainVO.getComaContractFlag() == 0) {
            contractMaitain.setComaPartyB((String) userCompanyInfoService.getAdminInfoFromRedis().get("uciDbid"));
        }
        if (contractMaintainVO.getComaContractFlag() > 0) {
            contractMaitain.setComaPartyA((String) userCompanyInfoService.getAdminInfoFromRedis().get("uciDbid"));
        }
        contractMaitain.setComaStatus("1");
        contractMaitain.setComaCreateUser(UserSession.getUserId());
        contractMaitain.setComaCreateTime(new Date());
        contractMaitain.setComaApproveStatus("0");
        contractMaitainMapper.insert(contractMaitain);
        contractFile.setCofoFileDbid(UUID.randomUUID().toString().replace("-", ""));
        contractFile.setContDbid(uuid);
        contractFileMapper.insert(contractFile);
        if (contractMaintainVO.getComaContractFlag() == 1) {
            deleteMat(uuid);
            List<ContractMat> contractMatList = contractMaintainVO.getContractMatList();
            batchInsert(contractMatList, uuid);
        }
        if (contractMaintainVO.getComaContractFlag() == 2) {
            ContractService contractService = new ContractService();
            BeanUtils.copyProperties(contractMaintainVO, contractService);
            contractService.setConSerDbid(UUID.randomUUID().toString().replace("-", ""));
            contractService.setContDbid(uuid);
            contractServiceMapper.insert(contractService);
        }
    }

    @Override
    @CiccLabel
    public ContractMaintainVO getByUuid(String uuid) {
        ContractMaintainVO contractMaintainVO = new ContractMaintainVO();
        ContractMaitain contractMaitain = contractMaitainMapper.selectById(uuid);
        contractMaitain.setComaContractType(CiccRecordUtil.getCiccRecord(CiccTableNameEnum.CONTRACT_TYPE.getCodeValue(), contractMaitain.getComaContractType()).getLabel());
        contractMaitain.setComaIsTaxLabel(CiccRecordUtil.getCiccRecord(CiccTableNameEnum.YES_NO.getCodeValue(), contractMaitain.getComaIsTax()).getLabel());
        contractMaitain.setComaApproveStatusLabel(CiccRecordUtil.getCiccRecord(CiccTableNameEnum.USE_STATUS.getCodeValue(), contractMaitain.getComaApproveStatus()).getLabel());
        contractMaitain.setComaPayTypeLabel(CiccRecordUtil.getCiccRecord(CiccTableNameEnum.PAY_TYPE.getCodeValue(), contractMaitain.getComaPayType()).getLabel());
        BeanUtils.copyProperties(contractMaitain, contractMaintainVO);
        QueryWrapper<ContractMat> wrapper1 = new QueryWrapper<>();
        wrapper1
                .eq("CONT_DBID", uuid);
        List<ContractMat> contractMatList = contractMatMapper.selectList(wrapper1);
        contractMaintainVO.setContractMatList(contractMatList);
        QueryWrapper<ContractService> wrapper2 = new QueryWrapper<>();
        wrapper2
                .eq("CONT_DBID", uuid);
        ContractService contractService = contractServiceMapper.selectOne(wrapper2);
        if (contractService != null) {
            BeanUtils.copyProperties(contractService, contractMaintainVO);
        }
        return contractMaintainVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ContractMaintainVO contractMaintainVO) {
        ContractMaitain contractMaitain = new ContractMaintainVO();
        BeanUtils.copyProperties(contractMaintainVO, contractMaitain);
        ContractFile contractFile = new ContractFile();
        BeanUtils.copyProperties(contractMaintainVO, contractFile);
        contractMaitain.setComaUpdateUser(UserSession.getUserId());
        contractMaitain.setComaUpdateTime(new Date());
        if (contractMaintainVO.getComaContractFlag() == 0) {
            contractMaitain.setComaPartyB((String) userCompanyInfoService.getAdminInfoFromRedis().get("uciDbid"));
        }
        if (contractMaintainVO.getComaContractFlag() > 0) {
            contractMaitain.setComaPartyA((String) userCompanyInfoService.getAdminInfoFromRedis().get("uciDbid"));
        }
        contractMaitainMapper.updateById(contractMaitain);
//        contractFileMapper.updateById(contractFile);
        if (contractMaintainVO.getComaContractFlag() == 1) {
            deleteMat(contractMaitain.getContDbid());
            List<ContractMat> contractMatList = contractMaintainVO.getContractMatList();
            batchInsert(contractMatList, contractMaitain.getContDbid());
        }
        if (contractMaintainVO.getComaContractFlag() == 2) {
            ContractService contractService = new ContractService();
            BeanUtils.copyProperties(contractMaintainVO, contractService);
            contractServiceMapper.updateById(contractService);
        }
    }

    /**
     * 根据合同id批量删除物料
     *
     * @param uuid
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteMat(String uuid) {
        QueryWrapper<ContractMat> wrapper = new QueryWrapper<>();
        wrapper
                .eq("CONT_DBID", uuid);
        contractMatMapper.delete(wrapper);
    }

    /**
     * 批量更新/插入数据
     *
     * @param contractMatList
     * @param uuid
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchInsert(List<ContractMat> contractMatList, String uuid) {
        if (contractMatList.size() > 0) {
            contractMatMapper.batchInsert(contractMatList.stream().peek((list) -> {
                list.setConMatDbid(list.getConMatDbid() == null ? UUID.randomUUID().toString().replace("-", "") : list.getConMatDbid());
                list.setContDbid(uuid);
                list.setCmCreateUser(list.getCmCreateUser() == null ? UserSession.getUserName() : list.getCmCreateUser());
                list.setCmCreateTime(list.getCmCreateTime() == null ? new Date() : list.getCmCreateTime());
                list.setCmUpdateUser(UserSession.getUserName());
                list.setCmUpdateTime(new Date());
            }).collect(Collectors.toList()));
        }
    }

    /**
     * 删除合同
     *
     * @param uuid
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(String uuid) {
        QueryWrapper<ContractMat> wrapper1 = new QueryWrapper<>();
        wrapper1
                .eq("CONT_DBID", uuid);
        contractMatMapper.delete(wrapper1);
        QueryWrapper<ContractService> wrapper2 = new QueryWrapper<>();
        wrapper2
                .eq("CONT_DBID", uuid);
        contractServiceMapper.delete(wrapper2);
        QueryWrapper<ContractFile> wrapper3 = new QueryWrapper<>();
        wrapper3
                .eq("CONT_DBID", uuid);
        contractFileMapper.delete(wrapper3);
        contractMaitainMapper.deleteById(uuid);
    }

    /**
     * 根据现实时间更新合同表，检查合同表时间是否已经超过当前时间，超过后status置0
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCheck() {
        Date now = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = simpleDateFormat.format(now);
        System.out.println(nowTime);
        contractMaitainMapper.updateCheck(nowTime);
    }

    /**
     * 根据企业资质类型获取企业dbid
     *
     * @param type
     * @return
     */
    @Override
    public List<UserCompanyInfo> getCompDbIdList(Integer type) {
        List<UserCompanyInfo> userCompanyInfoList = contractMaitainMapper.getCompDbIdList(type);
//        UserInfoToRedisMO userInfoToRedisMO = sysUserService.getUserInfoFromRedis(UserSession.getUserId());
        String uciDbid = contractMaitainMapper.selectUciDbid(UserSession.getUserId());
        for (int i = 0; i < userCompanyInfoList.size(); i++) {
            if (userCompanyInfoList.get(i).getUciDbid().equals(uciDbid)) {
                Collections.swap(userCompanyInfoList, 0, i);
                break;
            }
        }
        return userCompanyInfoList;
    }
}
